#!/bin/bash

date1=`date +%Y%m%d`
tlog1=/tmp/ip$date1.log
tlog2=/tmp/ip$date1-total.log

[[ -f ${tlog1} ]] && rm ${tlog1}
[[ -f ${tlog2} ]] && rm ${tlog2}

cat ip.txt.bak | while read line
do
    nf=$(echo ${line} | awk '{print NF}')
    if [ $nf -eq 1 ]; then
       stat=`nc -vzw 1 ${line} 22 &>> ${tlog1} && echo "\033[32msuccess\033[0m" || echo "\033[31merror\033[0m"`
    fi

    if [ $nf -eq 2 ]; then
       stat=`nc -vzw 1 ${line} &>> ${tlog1} && echo "\033[32msuccess\033[0m" || echo "\033[31merror\033[0m"`
    fi
    echo -e "${line} $stat" | tee -a  ${tlog2}
done

echo "**************"
echo "    error    "
echo "**************"
grep error ${tlog2}

#或者使用xargs命令完成脚本效果：cat ip.txt | xargs -P 20 -I {} nc -vz {} 22 2>/tmp/ip.log ; grep succeeded /tmp/ip.log 
#或者使用xargs命令完成脚本效果：cat ip.txt | xargs -P 20 -I {} nc -vz {} 22 2>/tmp/ip.log ; grep failed /tmp/ip.log                              
#如果ip.txt中包含IP 端口信息，则使用命令：cat ip.txt | xargs -P 20 -n 2 nc -vz 